<template>
  <Row class="layout-content-body">
    <dtable :columns="columns"
            :dataAll="dataAll"
            :dataShow="dataShow"
            add  assign
            @refresh="getall()"
            @add="add"
            @del="del"
            @edit="edit"
            @delCheck="delCheck" @assign="assign" v-loading="spinShow"></dtable>
    <Modal
      title="角色信息"
      v-model="editData"
      :loading="loading"
      :mask-closable="false" class="editm"
      @on-ok="asyncOK"
      @on-cancel="asyncCancel">
      <Form ref="editForm" :model="formItem" :label-width="80" :rules="ruleValidate">
        <Form-item label="名称" prop="Name">
          <Input v-model="formItem.Name" placeholder="请输入"></Input>
        </Form-item>
        <Form-item label="类型" prop="Type">
          <Radio-group v-model="formItem.Type">
            <Radio label="0">系统级</Radio>
            <Radio label="1">组织级</Radio>
            <Radio label="2">部门级</Radio>
            <Radio label="3">个人级</Radio>
          </Radio-group>
        </Form-item>
        <Form-item label="状态" prop="Status">
          <Radio-group v-model="formItem.Status">
            <Radio label="1">启用</Radio>
            <Radio label="0">停用</Radio>
          </Radio-group>
        </Form-item>
        <Form-item label="说明" prop="Remark">
          <Input v-model="formItem.Remark" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入...">
          </Input>
        </Form-item>
      </Form>
    </Modal>
    <Modal
      title="角色分配资源"
      v-model="assignData"
      :mask-closable="false" class="editm"
      @on-ok="assignOK"
    >
      <Tree ref="roleTree" :data="assignItem" multiple show-checkbox></Tree>


    </Modal>

  </Row>
</template>
<script>
  import api from '../../api'
  import {mapMutations, mapGetters, mapState} from 'vuex'
  import dtable from '../../components/table/dtable.vue'
  export default{
    data(){
      return {
        loading: true,//点击确定按钮时，确定按钮是否显示 loading 状态，开启则需手动设置visible来关闭对话框
        spinShow: false,//数据刷新遮罩层
        columns: [
          //多选框
          {
            type: 'selection',
            width: 60,
            align: 'center'
          },
          {
            title: '名称',
            key: 'Name',
            width: 280,
          },
          {
            title: '类型',
            key: 'Tname',
          },
          {
            title: '说明',
            key: 'Remark',
          },
          {
            title: '状态',
            key: 'Level',
            sortable: true,
            render (h, {row, column, index}) {
              // return `<span>${(row.Status === 1) ? '正常' : '停用'}</span>`;
              return h('span', {}, row.Status === 1 ? '正常' : '停用')
            }
          },
          // {
          //   title: '操作',
          //   key: 'action',
          //   width: 150,
          //   align: 'center',
          //   render (row, column, index) {
          //     return `<i-button type="primary" size="small" @click="edit(${index})">修改</i-button> <i-button type="error" size="small" @click="remove(${index})">删除</i-button>`;
          //   }
          // }
          {
            title: "操作",
            key: "action",
            width: 150,
            align: "center",
            render: (h, { row, column, index }) => {
              // return `<i-button type="primary" size="small" @click="edit(${index})">修改</i-button> <i-button type="error" size="small" @click="remove(${index})">删除</i-button>`;
              return h("div", [
                h(
                  "Button",
                  {
                    props: {
                      type: "primary",
                      size: "small"
                    },
                    on: {
                      click:() => {
                        // console.log(index)
                        this.edit(row);
                      }
                    }
                  },
                  "修改"
                ),
                h(
                  "Button",
                  {
                    props: {
                      type: "error",
                      size: "small"
                    },
                    on: {
                      click:() => {
                        this.remove(row);
                      }
                    }
                  },
                  "删除"
                )
              ]);
            }
          }
        ],//表格样式
        dataAll: [],//表格数据来源
        dataShow: true,//是否显示表格数据查看表单
        editData: false,//显示编辑表单
        formItem: {
          Name: '',
          Status: 1,
          Type:'3',
          Remark: ''
        },//数据编辑表单
        ruleValidate: {
          Name: [
            {required: true, message: '名称不能为空', trigger: 'blur'}
          ],
          Type: [
            {required: true, message: '类型不能为空', trigger: 'change'}
          ],
        },//数据编辑表单验证规则
        addid: 0,//0为修改模式，1为添加模式
        roleid: '',
        assignData: false,
        assignItem: []
      }
    },
    components: {
      dtable,
    },
    computed: {
      ...mapState(['isLogin', 'captchaUrl', 'cptId', 'msg']),
//      过滤数据
      filiterTableDate(){
        let e = this.dataAll.slice()
        let keys = this.searchKey
        let filterData = function (element) {
          if (keys === "") {
            return true
          }
          for (let o in element) {
            if (String(element[o]).indexOf(keys) >= 0) {
              return true
            }
          }
          return false
        }
        let fdata = e.filter(filterData)
        this.total = fdata.length
        return fdata
      },
//      当前显示数据
      curTableData() {
        let from = this.pageSize * (this.current - 1)
        let to = from + this.pageSize
        return this.filiterTableDate.slice(from, to)
      },
//      父资源名称
      parentRes() {
        let pr = [{Id: 0, Name: "根目录"}]
        for (let e in this.dataAll) {
          if (this.dataAll[e].Type === 1 && this.dataAll[e].Pid === 0) {
            pr.push({
              Name: this.dataAll[e].Name,
              Id: this.dataAll[e].Id
            })
          }
        }
        return pr
      },
      //状态数据转换
      fStauts(){
        if (this.formItem.Status === 1) {
          return true
        } else {
          return false
        }
      }
    },
    watch: {},
    methods: {
      //获取角色资源列表
      getResTree(id){
        api.getResource().then(response => {
          if (response.data.code === 0) {
            this.dataAll = response.data.Data
            this.total = (response.data.Data).length
          } else {
            this.$Message.error(this.msg)
          }
        })
      },
      //     获取资源名称
      getNameById(value) {
        let rname = ""
        if (value || '') {
          let rv = this.dataAll.filter((col, index) => col.Id === value)
          rname = rv[0].Name
        }
        return rname
      },
      getall (){
        this.spinShow = true
        api.getRole().then(response => {
          if (response.data.code === 0) {
            this.dataAll = response.data.Data
            this.total = (response.data.Data).length
          } else {
            this.$Message.error(this.msg)
          }
        })
        setTimeout(() => {
          this.spinShow = false;
        }, 1000);
      },
      edit(index){
        this.addid = 0
        this.formItem = index
        this.editData = true
      },
      add(){
        this.addid = 1
        this.$refs['editForm'].resetFields()
        this.editData = true
      },
      asyncOK(){
        this.$refs['editForm'].validate((valid) => {
          if (valid) {
            if (this.addid === 0) {
              api.updateRole(this.formItem).then(response => {
                if (response.data.code === 0) {
                  this.getall()
                  this.$Message.success(this.msg)
                } else {
                  this.$Message.error(this.msg, 4)
                }
              }, err => {
                this.$Message.error(this.msg, 4)
              })
            } else if (this.addid === 1) {
              api.addRole(this.formItem).then(response => {
                if (response.data.code === 0) {
                  this.getall()
                  this.$Message.success(this.msg)
                } else {
                  this.$Message.error(this.msg, 4)
                }
              }, err => {
                this.$Message.error(this.msg, 4)
              })
            }
            setTimeout(() => {
              this.editData = false;
            }, 1000);
          } else {
            this.$Message.error('表单验证失败!');
          }
        })
        this.$refs['editForm'].resetFields()
      },
      asyncCancel(){
        this.$refs['editForm'].resetFields()
        this.getall()
      },
      remove(row) {
        this.$Modal.confirm({
          title: '警告',
          content: '确认删除吗',
          onOk: () => {
            this.del(row)
          }
        })
      },
      del(row){
        api.deleteRole(row).then(response => {
          if (response.data.code === 0) {
            this.getall()
            this.$Message.success(this.msg)
          } else {
            this.$Message.error(this.msg, 4)
          }
        }, err => {
          this.$Message.error(this.msg, 4)
        })
      },
      delCheck(row){
        console.log("sdsdsds",row)
        api.deleteRoles(row).then(response => {
          if (response.data.code === 0) {
            this.getall()
            this.$Message.success(this.msg)
          } else {
            this.$Message.error(this.msg, 4)
          }
        }, err => {
          this.$Message.error(this.msg, 4)
        })
      },
      assign(row){
        if (row.length === 1) {
          this.roleid = row[0]
          api.GetRoleResourceTree(row[0]).then(response => {
            if (response.data.code === 0) {
              this.assignItem = response.data.Data.children
              this.assignData = true
            } else {
              this.$Message.error(this.msg, 4)
            }
          }, err => {
            this.$Message.error(this.msg, 4)
          })
        } else {
          this.$Message.error("角色授权必须选择一个角色进行授权！", 4)
        }

      },
      assignOK(){
          let rdata={}
          rdata['Roleid']=this.roleid
        console.log(this.roleid)
        rdata['Resources']=this.$refs.roleTree.getCheckedNodes()
        api.AssignResources(rdata).then(response => {
          if (response.data.code === 0) {
            this.$Message.success(this.msg)
          } else {
            this.$Message.error(this.msg, 4)
          }
        }, err => {
          this.$Message.error(this.msg, 4)
        })
//        console.log(this.$refs.roleTree.getCheckedNodes())
      },

    },
    mounted (){
      let self = this
      self.getall()
    }
  }
</script>
